package com.joe.demo.chat.server.handler;

import com.joe.demo.chat.message.GroupCreateRequestMessage;
import com.joe.demo.chat.message.GroupCreateResponseMessage;
import com.joe.demo.chat.server.factory.GroupSessionFactory;
import com.joe.demo.chat.server.session.Group;
import com.joe.demo.chat.server.session.IGroupSession;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.List;
import java.util.Set;

/**
 * @Description
 * @Author gaojw
 * @Date 2024-09-03
 */
@ChannelHandler.Sharable
public class GroupCreateRequestMessageHandler extends SimpleChannelInboundHandler<GroupCreateRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, GroupCreateRequestMessage groupCreateRequestMessage) throws Exception {
        final String groupName = groupCreateRequestMessage.getGroupName();
        final Set<String> memberSet = groupCreateRequestMessage.getMemberSet();

        // 群管理器
        final IGroupSession groupSession = GroupSessionFactory.getGroupSession();
        final Group group = groupSession.createGroup(groupName, memberSet);
        if (group == null){
            // 发送成功消息
            channelHandlerContext.writeAndFlush(new GroupCreateResponseMessage(true, groupName + " 创建成功"));

            // 发送拉群消息
            final List<Channel> membersChannel = groupSession.getMembersChannel(groupName);
            for (Channel channel : membersChannel) {
                channel.writeAndFlush(new GroupCreateResponseMessage(true, "您已被拉入" + groupName));
            }
        } else {
            channelHandlerContext.writeAndFlush(new GroupCreateResponseMessage(false, groupName + " 已经存在"));
        }

    }
}
